package cloud.xlh.infrastructure.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2023/1/19 10:33
 * @ Description: JSONObject工具类
 */
public class JSONObjectUtil {

    /**
     *
     * @param var1
     * @return com.alibaba.fastjson.JSONObject
     * @author XuLeHuang
     * @create 2023/1/19
     * @name: Object类型转JSONObject类型
     * @Description:
     **/
    public static JSONObject ObjectToJSONObject(Object var1) {
        return null;
    }

    /**
     *
     * @param var1
     * @return com.alibaba.fastjson.JSONObject
     * @author XuLeHuang
     * @create 2023/1/19
     * @name:  Java对象 转 JSON对象
     * @Description:
     **/
    public static JSONObject javaObjectToJSONObject(Object var1) {
        JSONObject jsonObject = (JSONObject) JSON.toJSON(var1);
        return jsonObject;
    }

    /**
     *
     * @param var1
     * @param var2
     * @return java.lang.Class
     * @author XuLeHuang
     * @create 2023/1/19
     * @name: JSON对象 转 Java对象
     * @Description:
     **/
    public static Object JSONObjectToJavaObject(JSONObject var1 , Class var2) {
        return JSON.toJavaObject(var1, var2);
    }

    /**
     *
     * @param var1
     * @return java.lang.String
     * @author XuLeHuang
     * @create 2023/1/19
     * @name: Java对象 转 JSON字符串
     * @Description:
     **/
    public static String javaObjectToJSONString(Object var1) {
        return JSON.toJSONString(var1);
    }

    /**
     *
     * @param var1
     * @param var2
     * @return java.lang.Object
     * @author XuLeHuang
     * @create 2023/1/19
     * @name: JSON字符串 转 Java对象
     * @Description:
     **/
    public static Object JSONStringToJavaObject(String var1 , Class var2) {
        return JSON.parseObject(var1,var2);
    }

    /**
     *
     * @param jsonStr json字符串
     * @param nodeKey 任意节点的key，例如head.retCode
     * @return java.lang.String
     * @author XuLeHuang
     * @create 2023/3/10
     * @name: 读取jsonStr任意节点值
     * @Description: 传入格式：xxx.xxx.xxx
     **/
    public static String getAnyNodeDataFromJsonStr(String jsonStr , String nodeKey) {
        String newNodeKey = nodeKey.replace(".", "/");
        newNodeKey = "/" + newNodeKey;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode jsonNode = objectMapper.readTree(jsonStr);
            String textValue = jsonNode.at(newNodeKey).textValue();
            return textValue;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("jsonNode读取json字符串任意节点值失败");
        }
    }
}
